package com.richpencil.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class uHttps {
	 /**
	 * 描述:向指定 URL 发送POST方法的请求 
	 * 说明:向指定 URL 发送POST方法的请求 
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲 
     * @param url 发送请求的 URL    
     * @param params 请求的参数集合     
     * @return 远程资源的响应结果
     */
	public static String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数            
            if (params != null) {
		          StringBuilder param = new StringBuilder();
		          for (Map.Entry<String, String> entry : params.entrySet()) {
		        	  if(param.length()>0){
		        		  param.append("&");
		        	  }	        	  
		        	  param.append(entry.getKey());
		        	  param.append("=");
		        	  param.append(entry.getValue());		        	  
		        	  //System.out.println(entry.getKey()+":"+entry.getValue());
		          }
		          //System.out.println("param:"+param.toString());
		          out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
	 /**
	 * 描述:向指定 URL 发送POST方法的请求(XML格式)
	 * 说明:向指定 URL 发送POST方法的请求(XML格式) 
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲 
     * @param url 发送请求的 URL    
     * @param str_Data 请求的XML参数     
     * @return 远程资源的响应结果
     */
	public static String sendPost(String url, String str_Data) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
		StringBuffer result = new StringBuffer();
        try {  
        	URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            /*conn.setDoOutput(true);  
			conn.setRequestProperty("Pragma:", "no-cache");  
			conn.setRequestProperty("Cache-Control", "no-cache");  
			conn.setRequestProperty("Content-Type", "text/xml"); */

            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(new String(str_Data.getBytes("UTF-8")));
            out.flush();  
            out.close();   
		    in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
		} 
        catch (Exception e) {
			System.out.println(e.getMessage().toString());
		}  
        return result.toString();
    }
	
	/**
	 * 描述:获取本机IP地址
	 * 说明:获取本机IP地址
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
		    ip = request.getHeader("Proxy-Client-IP");      
		}     
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
		    ip = request.getHeader("WL-Proxy-Client-IP");     
		}     
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
			ip = request.getRemoteAddr();      
		}   
		return ip;
    }
	/**
	 * 描述:在页面中进行alert操作
	 * 说明:在页面中进行alert操作
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲
	 * @param response
	 * @param str_Msg
	 * @throws Exception
	 */
	public static void PrintWriterAlert(HttpServletResponse response, String str_Msg){
		try{
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print("<script>alert('" + str_Msg + "');</script>");
			out.flush();
			out.close();
		}
		catch(Exception ex){
			
		}
	}
	
	/**
	 * 描述:通过SubMail发送短信
	 * 说明:通过SubMail发送短信
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲
	 * @param PhoneNumber手机号码
	 * @param SubMailMsgCode在SubMail短信模板的对应编码
	 * @param Param传输参数,在SubMail短信模板中，对应的自定义参数，注：参数Key与参数数量要与模板一致
	 * @return Map(status状态【success成功】、send_id返回短信唯一编码、fee该短信所占短信条数【一条短信上线限67字】、sms_credits剩余短信条数)
	 */
	/*public static Map SubMailMessageXSend(String PhoneNumber, String SubMailMsgCode,
			Map Param){
		Map result = new HashMap();
		try{
			AppConfig config = new AppConfig();
			config.setAppId(MessageConfig.APP_ID);
			config.setAppKey(MessageConfig.APP_KEY);
			config.setSignType(MessageConfig.APP_SIGNTYPE);
			MESSAGEXsend submail = new MESSAGEXsend(config);
			submail.addTo(PhoneNumber);
			submail.setProject(SubMailMsgCode);
			if(Param.size() > 0){
				Set<String> keySet = Param.keySet();
				for(String key : keySet){
					String str_ParamValue = Param.get(key).toString();
					submail.addVar(key, str_ParamValue);
				}
			}
			result = submail.customxsend();
		}
		catch(Exception ex){
			result = new HashMap();
		}
		return result;
	}*/
	
	/**
	 * 描述:通过SubMail发送短信【群发】
	 * 说明:通过SubMail发送短信【群发】
	 * 最近修改时间:	2016-10-21
	 * 修改者：王丘轲
	 * 创建时间：2016-10-21
	 * 创建者：王丘轲
	 * @param PhoneNumber手机号码【可多个】
	 * @param SubMailMsgCode在SubMail短信模板的对应编码
	 * @param Param传输参数,在SubMail短信模板中，对应的自定义参数，注：参数Key与参数数量要与模板一致
	 * @return Map(status状态【success成功】、send_id返回短信唯一编码、fee该短信所占短信条数【一条短信上线限67字】、sms_credits剩余短信条数)
	 *//*
	public static Map SubMailMessageMultiXSend(List<String> PhoneNumber, String SubMailMsgCode,
			Map Param){
		Map result = new HashMap();
		try{
			AppConfig config = new AppConfig();
			config.setAppId(MessageConfig.APP_ID);
			config.setAppKey(MessageConfig.APP_KEY);
			config.setSignType(MessageConfig.APP_SIGNTYPE);
			MESSAGEXsend submail = new MESSAGEXsend(config);
			submail.setProject(SubMailMsgCode);
			List<Map> list_Map = new ArrayList();
			for(String str_PhoneNumber : PhoneNumber){
				Map map = new HashMap();
				map.put("to", str_PhoneNumber);
				map.put("vars", Param);
				list_Map.add(map);
			}
			//System.out.println(list_Map.toString());
			//System.out.println(uStrings.Map2Json(list_Map));
			submail.setMulti(uStrings.Map2Json(list_Map));
			result = submail.custommultixsend();
		}
		catch(Exception ex){
			result = new HashMap();
		}
		return result;
	}*/
	
	/**
	 * 描述：检查文件大小(基于EasyUI的FileBox)
	 * 说明：超过false、未超过true
	 * 最近修改时间:	2016-11-08
	 * 修改者：王丘轲
	 * 创建时间：2016-11-08
	 * 创建者：王丘轲
	 * @param request
	 * @param name名称
	 * @param size大小(kb)
	 * @return
	 */
	public boolean CheckFileSize(HttpServletRequest request, String name, int size)
	{
		int int_FileSize = getFileSize(request, name);
		if(int_FileSize > 1024 * size)
		{
			return false;
		}
		else {
			return true;
		}
	}
	
	/**
	 * 描述：获取文件大小(基于EasyUI的FileBox)
	 * 说明：获取文件大小(基于EasyUI的FileBox)
	 * 最近修改时间:	2016-11-08
	 * 修改者：王丘轲
	 * 创建时间：2016-11-08
	 * 创建者：王丘轲
	 * @param request
	 * @param name名称
	 * @return
	 */
	public static int getFileSize(HttpServletRequest request, String name){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile(name);
		return (int) file.getSize();
	}
	
	/**
	 * 描述：上传图片
	 * 说明：上传图片
	 * 最近修改时间:	2016-11-08
	 * 修改者：王丘轲
	 * 创建时间：2016-11-08
	 * 创建者：王丘轲
	 * @param request
	 * @param Name EasyUI的FileBox的Id
	 * @param savePath 保存路径
	 * @return
	 */
	public static String uploadFile(HttpServletRequest request, String fileBoxId, String savePath) {
		String path = "";
		try{
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//名
			String str_ImageName = df.format(new Date());//名
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//获取文件
			MultipartFile file = multipartRequest.getFile(fileBoxId);//获取文件
			String suffix = file.getContentType().substring(file.getContentType().lastIndexOf('/') + 1);//获得后缀
			String dirFile = request.getSession().getServletContext().getRealPath("/")
						   + savePath;//文件路径
			File fileSave = new File(dirFile);
			//判断路径是否存在在
			if(!fileSave.exists()){
				fileSave.mkdirs();
			}
			File uploadFile = new File(dirFile, str_ImageName + "." + suffix);//完整保存路径
			InputStream is = file.getInputStream();
			FileOutputStream fos = new FileOutputStream(uploadFile);
			byte[] tmp = new byte[1024];
			int len = -1;
			while ((len = is.read(tmp)) != -1) {
				fos.write(tmp, 0, len);
			}
			fos.flush();
			is.close();
			fos.close();
			String str_FullPath = savePath + "/" + str_ImageName + "." + suffix;
			path = str_FullPath.replace("//", "/");
		}
		catch(Exception ex){
			path = "";
		}
		return path;
	}
	/**
	 * 描述：上传图片
	 * 说明：上传图片
	 * 最近修改时间:	2016-12-28
	 * 修改者：王丘轲
	 * 创建时间：2016-12-28
	 * 创建者：王丘轲
	 * @param request
	 * @param Name EasyUI的FileBox的Id
	 * @param savePath 保存完整路径
	 * @return
	 */
	public static String uploadFileDir(HttpServletRequest request, String fileBoxId, String savePath) {
		String path = "";
		try{
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//名
			String str_ImageName = df.format(new Date());//名
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//获取文件
			MultipartFile file = multipartRequest.getFile(fileBoxId);//获取文件
			String suffix = file.getContentType().substring(file.getContentType().lastIndexOf('/') + 1);//获得后缀
			String dirFile = savePath;//文件路径
			File fileSave = new File(dirFile);
			//判断路径是否存在在
			if(!fileSave.exists()){
				fileSave.mkdirs();
			}
			File uploadFile = new File(dirFile, str_ImageName + "." + suffix);//完整保存路径
			InputStream is = file.getInputStream();
			FileOutputStream fos = new FileOutputStream(uploadFile);
			byte[] tmp = new byte[1024];
			int len = -1;
			while ((len = is.read(tmp)) != -1) {
				fos.write(tmp, 0, len);
			}
			fos.flush();
			is.close();
			fos.close();
			String str_FullPath = savePath + "/" + str_ImageName + "." + suffix;
			path = str_FullPath.replace("//", "/");
		}
		catch(Exception ex){
			path = "";
		}
		return path;
	}
	/**
	 * 描述：上传图片
	 * 说明：上传图片
	 * 最近修改时间:	2016-12-28
	 * 修改者：李鹏辉
	 * 创建时间：2016-12-28
	 * 创建者：李鹏辉
	 * @param request
	 * @param Name EasyUI的FileBox的Id
	 * @param savePath 保存完整路径
	 * @return
	 */
	public static String uploadFileReturnFileName(HttpServletRequest request, String fileBoxId, String savePath) {
		String path = "";
		try{
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//名
			String str_ImageName = df.format(new Date());//名
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//获取文件
			MultipartFile file = multipartRequest.getFile(fileBoxId);//获取文件
			String suffix = file.getContentType().substring(file.getContentType().lastIndexOf('/') + 1);//获得后缀
			String dirFile = savePath;//文件路径
			File fileSave = new File(dirFile);
			//判断路径是否存在在
			if(!fileSave.exists()){
				fileSave.mkdirs();
			}
			File uploadFile = new File(dirFile, str_ImageName + "." + suffix);//完整保存路径
			InputStream is = file.getInputStream();
			FileOutputStream fos = new FileOutputStream(uploadFile);
			byte[] tmp = new byte[1024];
			int len = -1;
			while ((len = is.read(tmp)) != -1) {
				fos.write(tmp, 0, len);
			}
			fos.flush();
			is.close();
			fos.close();
			path = str_ImageName + "." + suffix;
		}
		catch(Exception ex){
			path = "";
		}
		return path;
	}
	/**
	 * 描述：获取完整路径
	 * 说明：项目所在路径+指定路径
	 * 最近修改时间:	2016-11-08
	 * 修改者：王丘轲
	 * 创建时间：2016-11-08
	 * 创建者：王丘轲
	 * @param request HttpServletRequest
	 * @param path指定路径,可空
	 * @return
	 */
	public static String getFullPath(HttpServletRequest request, String path){
		String result = "";
		try{
			result = request.getSession().getServletContext().getRealPath("/") + path;
			result = result.replace("\\", "/");
			result = result.replace("//", "/");
		}
		catch(Exception ex){
			result = "";
		}
		return result;
	}
}
